import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'
import { saveAs } from 'file-saver'
import store from '@/store'
// import { getToken } from '@/utils/auth'

// 创建一个axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000, // request timeout
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'fromType': 'PC'
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
   
    if (response.request.responseType === 'blob') {
      return response.data
    }
    // console.log(res)
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 0) {
      if (res.code === 2) {
        MessageBox.confirm('你的账号已在别处登录，如非本人操作，请立刻修改密码', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            if (location.href.indexOf('/login') === -1) {
              location.reload()
            }
          })
        })
      } else if (res.code == 24 && res.msg == '获取用户最新开票信息失败') {

      } else {
        Message({
          message: res.msg || 'Error',
          type: 'error',
          duration: 3 * 1000
        })
      }

      return Promise.reject(res || 'Error')
    } else {
      return res
    }
  },
  (error) => {
    const messages =
      error && error.response && error.response.msg && error.response.msg
        ? error.response.msg
        : '请求失败，服务器好像出了点小问题~，请稍后再试'
    Message({
      message:messages,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)
// 通用下载方法
export function download(url, params, filename, config) {
  // let downloadLoadingInstance = Loading.service({
  //   text: '正在下载数据，请稍候',
  //   spinner: 'el-icon-loading',
  //   background: 'rgba(0, 0, 0, 0.1)',
  // })
    let promise = new Promise((resolve, reject) => {
      service
      .post(url, params, {
        transformRequest: [
          (params) => {
            return tansParams(params)
          },
        ],
        headers: { 'Content-Type': 'application/x-www-form-urlencoded','Content-Security-Policy': 'upgrade-insecure-requests' },
        responseType: 'blob',
        ...config,
      })
      .then(async (data) => {
        if (data.type !== 'application/json') {
          const blob = new Blob([data])
          saveAs(blob, filename)
          // downloadLoadingInstance.close()
          resolve(data)
        } else {
          const resText = await data.text()
          const rspObj = JSON.parse(resText)
          const errMsg = rspObj.msg || '下载文件出现错误'
          Message.error(errMsg)
          // downloadLoadingInstance.close()
          reject(r)
        } 
      })
      .catch((r) => {
        console.error(r)
        // Message.error('下载文件出现错误，请联系管理员！')
        // downloadLoadingInstance.close()
        reject(r)
      })
    })
    return promise
  return 
}
function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    var part = encodeURIComponent(propName) + '='
    if (value !== null && value !== '' && typeof value !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (
            value[key] !== null &&
            value[key] !== '' &&
            typeof value[key] !== 'undefined'
          ) {
            let params = propName + '[' + key + ']'
            var subPart = encodeURIComponent(params) + '='
            result += subPart + encodeURIComponent(value[key]) + '&'
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&'
      }
    }
  }
  return result
}
export default service
